package com.itheima.dao.impl;

import com.itheima.dao.IAccountDao;
import com.itheima.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;


import java.util.List;


/*基于注解的方式*/
@Component
public class AccountDaoImpl3 implements IAccountDao {
    @Autowired
    IAccountDao accountDao;

    @Autowired
    private JdbcTemplate jdbcTemplate;



    public Account findAccountById(Integer account) {
        List<Account> list = jdbcTemplate.query("select * from account where id=?",
                new BeanPropertyRowMapper<Account>(Account.class),account);

        return list.isEmpty()?null:list.get(0);
    }

    public Account findAccountByName(String accountName) {
        List<Account> list = jdbcTemplate.query("select * from account where name=?",
                new BeanPropertyRowMapper<Account>(Account.class),accountName);
        if(list.isEmpty()){
            return null;
        }
        if(list.size()>1){
            throw new RuntimeException("结果集不唯一");

        }
        return list.get(0);

    }

    public void updateAccount(Account account) {
    jdbcTemplate.update("update account set name=?,money=? where id=?",
        account.getName(),account.getMoney(),account.getId());
    }

    /**
     * 转账
     * @param inName
     * @param outName
     * @param money
     */

    public void transfer(String inName, String outName, Float money) {
        //1根据名称查询转出账户
        Account account2 = accountDao.findAccountByName(outName);
        //2根据名称查询转入账户
        Account account = accountDao.findAccountByName(inName);
        //3转出账户减钱
        account2.setMoney(account2.getMoney()-money);
        //4转入账户加钱
        account.setMoney(account.getMoney()+money);
        //5更新转出账户
        accountDao.updateAccount(account2);

        int i=3/0;
        //6跟新转入账户
        accountDao.updateAccount(account);
    }
}
